import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/device_model.dart';

class DrawRecordPage extends StatefulWidget {
  DrawRecordPage({this.id, this.device_name});
  final String device_name;
  final int id;
  @override
  _DrawRecordPageState createState() => new _DrawRecordPageState(id, device_name);
}

class _DrawRecordPageState extends State<DrawRecordPage> {
  double totalOutcome = 0.0;
  List outcomeArr = [];
  int nextPage = 0;
  int hasData = 2;
  final int id;
  final String device_name;
  DeviceModel device;
  ScrollController _scrollController = new ScrollController();

  _DrawRecordPageState(this.id, this.device_name) {
    print(this.device_name);
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        print("到底了");
      }
    });
    initDevice();
  }
  initDevice() async {
    this.device = new DeviceModel().fromMap(await findDeviceById(id));
    drawRecord();
  }

  drawRecord() async {
    var isLogin = await checkLogin(device.sessionid, device.userid);
    bool loginStatus = true;
    if (!isLogin) {
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      print("登录有效");
      var drawData = await getDrawRecord(device.sessionid, device.userid);
      this.outcomeArr = drawData['outcomeArr'];
      if (this.outcomeArr.length > 0) {
        this.hasData = 1;
      } else {
        this.hasData = 0;
      }
      this.totalOutcome = double.parse(drawData['totalOutcome']);
      this.nextPage = drawData['nextPage'];
      setState(() {});
    } else {
      showDialog<Null>(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text("错误提醒"),
            content: new Text("获取提币记录失败，请重试"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () async {
                  drawRecord();
                },
                child: new Text(
                  '重试',
                ),
              ),
              new FlatButton(
                onPressed: () async {
                  Navigator.of(context).pop();
                },
                child: new Text(
                  '返回',
                ),
              ),
            ],
          );
        },
      );
    }
  }

  Widget _buildTiles(Map outcome) {
    return new Column(
      children: <Widget>[
        new ListTile(
          title: new Text(
            outcome['originBalance'].toString(),
            style: new TextStyle(fontSize: 22.0, color: Colors.deepOrangeAccent),
          ),
          subtitle: new Text(outcome['updateTime']),
          trailing: new Text(
            outcome['status'] == 2 ? "已到账" : "提币中",
            style: new TextStyle(color: outcome['status'] == 2 ? Colors.green : Colors.black),
          ),
        ),
        Divider(height: 1.0),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        accentColor: Colors.deepOrange,
        primaryColor: Colors.deepOrange,
      ),
      home: new Scaffold(
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: Colors.deepOrange,
          middle: new Text(
            (this.device_name ?? "") + "提币记录",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),
          leading: new CupertinoButton(
            padding: EdgeInsets.all(0.0),
            child: new Icon(
              CupertinoIcons.back,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.pop(context, "0");
            },
          ),
        ),
        body: this.hasData == 1
            ? new ListView.builder(
                controller: _scrollController,
                physics: const AlwaysScrollableScrollPhysics(),
                itemCount: outcomeArr.length,
                itemBuilder: (context, i) => _buildTiles(outcomeArr[i]),
              )
            : this.hasData == 2
                ? new Center(
                    child: new CircularProgressIndicator(),
                  )
                : new Center(
                    child: new Container(
                        width: 200.0,
                        height: 200.0,
                        child: new Column(
                          children: <Widget>[
                            new Text(
                              "暂无提币记录",
                              style: new TextStyle(fontSize: 22.0),
                            ),
                            new FlatButton(
                                onPressed: () {
                                  Navigator.of(context).pop();
                                },
                                child: new Text("返回")),
                          ],
                        )),
                  ),
//          child:
      ),
    );
  }
}
